package cn.nexttec.noteplayer.ui.VideoFile

import android.content.ServiceConnection
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.nexttec.noteplayer.databases.dao.VideoFileDao
import cn.nexttec.noteplayer.injection.IoDispatcher
import cn.nexttec.noteplayer.models.VideoFileInfo
import cn.nexttec.noteplayer.service.FileScanService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class FileViewModel @Inject constructor(
    val videoFileDao: VideoFileDao,
    @IoDispatcher val ioDispatcher: CoroutineDispatcher
) : ViewModel() {

    private val _files = MutableLiveData<List<VideoFileInfo>>()
    val files: LiveData<List<VideoFileInfo>> get() = _files
    private val _topFiles = MutableLiveData<List<VideoFileInfo>>()
    val topFiles: LiveData<List<VideoFileInfo>> get() = _topFiles

    fun loadFiles() {
        viewModelScope.launch(ioDispatcher) {
            var fileInfos: List<VideoFileInfo>? = videoFileDao.getVideos()
            withContext(Dispatchers.Main) {
                _topFiles.value = fileInfos!!
            }
        }
    }

    fun loadDirectory(directory: VideoFileInfo) {
        viewModelScope.launch(ioDispatcher) {
            val fileInfos = videoFileDao.getVideoFilesByPath(directory.path)
            withContext(Dispatchers.Main) {
                _files.value = fileInfos
            }
        }
    }

    fun scan(){

    }
}